<template>
	<div class="ebook-reader">
		<!-- {{$route.params.fileName}}   -->
		<div id="read"></div>
		<div class="ebook-reader-mask" 
			@click="onMaskClick"
			@touchmove="move"
			@touchend="moveEnd"
			@mousedown.left="onMouseEnter"
			@mousemove.left="onMoseMove"
			@mouseup.left="onMouseEnd"></div>
	</div>
</template>

<script>
// import { mapActions } from 'vuex'
// import { mapGetters } from 'vuex'
// 导入mixin设置vuex模块
import { ebookMixin } from '../../utils/mixin'
import Epub from 'epubjs'
import { getFontFamily, getFontSize, getLocation, getTheme, saveFontFamily, saveFontSize, saveTheme } from '../../utils/localStorage'
import { flatten } from '../../utils/book'
import { getLocalForage } from '../../utils/localForage'
global.ePub = Epub
export default {
	mixins: [ebookMixin],
	methods: {
		// 1-鼠标进入
		// 2-鼠标进入后移动
		// 3-鼠标从移动状态松手
		// 4-鼠标还原
		onMouseEnd(e) {
			if (this.mouseState === 2) {
				this.setOffsetY(0) // 还原Y轴的偏移量
				this.firstOffsetY = null
				this.mouseState = 3
			} else {
				this.mouseState = 4
			}
			const time = e.timeStamp - this.mouseStateTime
			if (time < 200) { // 移动时间小于200毫秒时视为点击事件
				this.mouseState = 4
			}
			e.preventDefault()
			e.stopPropagation()
		},
		onMoseMove(e) {
			if (this.mouseState === 1) {
				this.mouseState = 2 // 切换状态为2
			} else if (this.mouseState === 2) {
				let offsetY = 0 // Y轴的偏移量
				if (this.firstOffsetY) {
					offsetY = e.clientY - this.firstOffsetY
					this.setOffsetY(offsetY)
				} else {
					this.firstOffsetY = e.clientY
				}
			}
			// 阻止鼠标的默认行为
			e.preventDefault()
			e.stopPropagation()
		},
		onMouseEnter(e) {
			this.mouseState = 1
			this.mouseStateTime = e.timeStamp
			e.preventDefault()
			e.stopPropagation()
		},
		move(e) {
			let offsetY = 0 // Y轴的偏移量
			if (this.firstOffsetY) {
				offsetY = e.changedTouches[0].clientY - this.firstOffsetY
				this.setOffsetY(offsetY)
			} else {
				this.firstOffsetY = e.changedTouches[0].clientY
			}
			e.preventDefault()
			e.stopPropagation()
		},
		moveEnd(e) {
			this.setOffsetY(0) // 还原Y轴的偏移量
			this.firstOffsetY = null
		},
		onMaskClick(e) {
			if (this.mouseState && (this.mouseState === 2 || this.mouseState === 3)) {
				return
			}
			const offsetX = e.offsetX
			const width = window.innerWidth
			if (offsetX > 0 && offsetX < width * 0.3) { // 点击左侧切换到上一页
				this.prevPage()
			} else if (offsetX > 0 && offsetX > width * 0.7) { // 点击右侧切切换到下一页
				this.nextPage()
			} else {
				this.toggleTitleAndMenu()
			}
		},
		// ...mapActions(['setMenuVisible']),
		prevPage() {
			if (this.rendition) {
				this.rendition.prev().then(() => {
					this.refreshLocation()
				})
				this.hideTitleAndMenu()
			}
		},
		nextPage() {
			if (this.rendition) {
				this.rendition.next().then(() => {
					this.refreshLocation()
				})
				this.hideTitleAndMenu()
			}
		},
		toggleTitleAndMenu() {
			if (this.menuVisible) {
				// 菜单栏隐藏时字体菜单栏隐藏
				this.setSettingVisible(-1)
				// 点击屏幕隐藏字体设置菜单栏
				this.setFontFamilyVisible(false)
			}
			// 控制阅读器上侧的菜单栏的显示与隐藏
			// this.$store.dispatch('setMenuVisible', !this.menuVisible)
			this.setMenuVisible(!this.menuVisible)
		},
		initFontSize() { // 字号数据处理的方法
			let fontSize = getFontSize(this.fileName)
			if (!fontSize) {
				saveFontSize(this.fileName, this.defaultFontFamily)
			} else {
				// 读取到localStorage中的字体数据并设置书籍字体
				this.rendition.themes.fontSize(fontSize)
				// 更新显示的数据
				this.setDefaultFontSize(fontSize)
			}
		},
		initFontFamily() { // 字体数据处理的方法
			let font = getFontFamily(this.fileName)
			if (!font) {
				saveFontFamily(this.fileName, this.defaultFontFamily)
			} else {
				// 读取到localStorage中的字体数据并设置书籍字体
				this.rendition.themes.font(font)
				// 更新显示的数据
				this.setDefaultFontFamily(font)
			}
		},
		initTheme() { // 注册主题
			// 获取组题的缓存值
			let defaultTheme = getTheme(this.fileName)
			if (!defaultTheme) {
				// 存入缓存
				defaultTheme = this.themeList[0].name
				saveTheme(this.fileName, defaultTheme)
			}
			this.setDefaultTheme(defaultTheme)
			this.themeList.forEach(theme => {
				this.rendition.themes.register(theme.name, theme.style)
			})
			// 设置默认样式
			this.rendition.themes.select(defaultTheme)
		},
		initRendition() {
			this.rendition = this.book.renderTo('read', {
				width: innerWidth,
				height: innerHeight,
				method: 'default'
			})
			const location = getLocation(this.fileName)
			this.display(location, () => {
				// 存入组题
				this.initTheme()
				// 存入字号数据
				this.initFontSize()
				// 存入字体数据
				this.initFontFamily()
				// 初始化全局样式
				this.initGlobalStyle()
				// 定于到保存的进度
				this.refreshLocation()
			})
			// 引入字体样式必须采用url地址的方式
			// this.rendition.hooks.content.register(contents => {
			// 	contents.addStylesheet('http://127.0.0.1:8081/fonts/daysOne.css')
			// })
			// this.rendition.hooks.content.register(contents => {
			// 	contents.addStylesheet('http://127.0.0.1:8081/fonts/cabin.css')
			// })
			// this.rendition.hooks.content.register(contents => {
			// 	contents.addStylesheet('http://127.0.0.1:8081/fonts/montserrat.css')
			// })
			// this.rendition.hooks.content.register(contents => {
			// 	contents.addStylesheet('http://127.0.0.1:8081/fonts/tangerine.css')
			// })
			this.rendition.hooks.content.register(contents => {
				Promise.all([
					contents.addStylesheet(`${process.env.VUE_APP_RES_URL}/fonts/daysOne.css`),
					contents.addStylesheet(`${process.env.VUE_APP_RES_URL}/fonts/cabin.css`),
					contents.addStylesheet(`${process.env.VUE_APP_RES_URL}/fonts/montserrat.css`),
					contents.addStylesheet(`${process.env.VUE_APP_RES_URL}/fonts/tangerine.css`)
				]).then(() => {
				})
			})
		},
		initGesture() { // 手势的方法
			this.rendition.on('touchstart', event => {
				// 获取触摸开始时的x轴坐标
				this.touchStartX = event.changedTouches[0].clientX
				// 获取触摸的开始时间
				this.touchStartTime = event.timeStamp
				// console.log(event);
				// console.log(e);
			})
			this.rendition.on('touchend', event => {
				// 获取触摸结束时的x轴坐标
				this.touchEndX = event.changedTouches[0].clientX
				// 获取触摸的开始时间
				this.touchEndTime = event.timeStamp
				const offsetX = this.touchEndX - this.touchStartX
				const time = this.touchEndTime - this.touchStartTime
				// console.log(offsetX, time);
				if (time < 500 && offsetX > 40) {
					this.prevPage()
				} else if (time < 500 && offsetX < -40) {
					this.nextPage()
				} else {
					this.toggleTitleAndMenu()
				}
				event.preventDefault()
				event.stopPropagation()
			})
		},
		parseBook() {
			// 获取图书的封面
			this.book.loaded.cover.then(cover => {
				this.book.archive.createUrl(cover).then(url => {
					this.setCover(url)
				})
			})
			this.book.loaded.metadata.then(metadata => {
				this.setMetadata(metadata)
			})
			// 获取图书的目录
			this.book.loaded.navigation.then(nav => {
				const navItem = flatten(nav.toc)
				// 封装结局一维数组层级的方法
				function find(item, level = 0) {
					return !item.parent ? level : find(navItem.filter(parentItem => parentItem.id === item.parent)[0], ++level)
				}
				navItem.forEach(item => {
					item.level = find(item)
				})
				// 将处理后的值传入vuex中
				this.setNavigation(navItem)
			})
		},
		initEpub(url) {
			// console.log(url);
			this.book = new Epub(url)
			this.setCurrentBook(this.book)
			this.initRendition()
			this.initGesture()
			this.parseBook()
			this.book.ready.then(() => {
				// 设置分页算法
				return this.book.locations.generate(750 * (window.innerWidth / 375) * (getFontSize(this.fileName) / 16)).then(locations => {
					this.navigation.forEach(nav => {
						nav.pageList = []
					})
					// console.log(locations)
					locations.forEach(item => {
						const loc = item.match(/\[(.*)\]!/)[1]
						this.navigation.forEach(nav => {
							if (nav.href) {
								// const href = nav.href.match(/^(.*)\.html$/)[1]
								// if (href === loc) {
								// 	nav.pageList.push(item)
								// }
								const href = nav.href.match(/^(.*)\.html$/)
                if (href) {
                  if (href[1] === loc) {
                    nav.pagelist.push(item)
                  }
                }
							}
						})
						let currentPage = 1
						this.navigation.forEach((nav, index) => {
							if (index === 0) {
								nav.page = 1
							} else {
								nav.page = currentPage
							}
							currentPage += nav.pageList.length + 1
						})
					})
					this.setPagelist(locations)
					this.setBookAvailable(true)
					// 分页完成后刷新进度条
					this.refreshLocation()
				})
			})
		}
	},
	mounted() {
		const books = this.$route.params.fileName.split('|')
		// const fileName = this.$route.params.fileName.split('|').join('/')
		const fileName = books[1]
		// 从IndexDB中获取缓存书籍
		getLocalForage(fileName, (err, blob) => {
			if (!err && blob) {
				// console.log('找到离线缓存电子书')
				this.setFileName(books.join('/')).then(() => {
					this.initEpub(blob)
				})
			} else {
				// console.log('在线获取电子书')
				this.setFileName(books.join('/')).then(() => {
					// const url = process.env.VUE_APP_RES_URL + '/epub/' + this.fileName + '.epub'
					// 生产环境的配置
					const url = process.env.VUE_APP_EPUB_URL + '/' + this.fileName + '.epub'
					this.initEpub(url)
				})
			}
		})
		// console.log(fileName);
		// this.$store.dispatch('setFileName', fileName).then(() => {
		// 	this.initEpub()
		// })
	}
}
</script>

<style lang="scss" scoped>
// @import url();
@import "../../assets/styles/global.scss";
.ebook-reader {
  width: 100%;
  height: 100%;
  overflow: hidden;
	// z-index: 1;
  .ebook-reader-mask {
    position: absolute;
    top: 0;
    left: 0;
    background: transparent;
    z-index: 150;
    width: 100%;
    height: 100%;
  }
}
</style>
